package com.atguigu.test.processor;

import com.atguigu.test.annotation.LENGTH;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zp
 * @version 1.0
 * @description: TODO
 * @date 2022/12/24 20:37
 */
@Slf4j
public class MyVerifyBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 是否引用ApiModelProperty注解
            if(field.isAnnotationPresent(LENGTH.class)){
                field.setAccessible(true);
                try {
                    Object o = field.get(bean);
                    String s = String.valueOf(o);
                    LENGTH length = field.getAnnotation(LENGTH.class);
                    int max = length.max();
                    int min = length.min();

                    if(s.length()>max){
                        throw new UnsatisfiedLinkError("大于最长");
                    }
                    if(s.length()<min){
                        throw new UnsatisfiedLinkError("小于于最长");
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
    }
}
